package com.beiding.controller.user;

import com.beiding.service.Authorities;
import com.beiding.service.user.UserService;
import com.google.common.collect.Sets;
import org.apache.commons.collections.collection.UnmodifiableCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Collection;
import java.util.HashSet;

@RestController
@RequestMapping("/agreement")
public class AgreementRestController {


    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    //当用户同意某个协议的时候就为其添加对应的权限

    @PostMapping("/landlord-agree")
    @Secured("ROLE_USER")
    void landlord(Principal principal, HttpSession session) {

        //设置Session,添加当前用户的权限
        userService.addAuthority(principal.getName(), addAuthority(session, "landlord"));
    }


    @PostMapping("/tenant-agree")
    @Secured("ROLE_USER")
    void tenant(Principal principal, HttpSession session) {
        userService.addAuthority(principal.getName(), addAuthority(session, "tenant"));
    }


    private GrantedAuthority addAuthority(HttpSession session, String auth) {


        SecurityContextImpl context = (SecurityContextImpl) session.getAttribute("SPRING_SECURITY_CONTEXT");

        GrantedAuthority authority = Authorities.of(auth);

        Authentication authentication = context.getAuthentication();

        HashSet<GrantedAuthority> set = Sets.newHashSet(authentication.getAuthorities());

        set.add(authority);

        Collection decorate = UnmodifiableCollection.decorate(set);

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), decorate);

        context.setAuthentication(token);

        session.setAttribute("SPRING_SECURITY_CONTEXT", context);

        return authority;
    }


}
